<template>
  <view class="stats-container">
    <!-- 头部 -->
    <view class="stats-header">
      <text class="stats-title">学习任务统计分析</text>
      <text class="stats-subtitle">数据可视化展示您的学习进度与任务完成情况</text>
    </view>
    
    <!-- 概览卡片 -->
    <view class="overview-cards">
      <view class="stat-card">
        <view class="card-icon">
          <uni-icons type="list" size="24" color="#7a9bb5"></uni-icons>
        </view>
        <text class="card-value">{{ totalTasks }}</text>
        <text class="card-label">总任务数</text>
      </view>
      
      <view class="stat-card">
        <view class="card-icon">
          <uni-icons type="checkbox-filled" size="24" color="#6b9273"></uni-icons>
        </view>
        <text class="card-value">{{ completedTasks }}</text>
        <text class="card-label">已完成</text>
      </view>
      
      <view class="stat-card">
        <view class="card-icon">
          <uni-icons type="clock" size="24" color="#d4b876"></uni-icons>
        </view>
        <text class="card-value">{{ onTimeRate }}%</text>
        <text class="card-label">按时完成率</text>
      </view>
    </view>
    
    <!-- 按时完成率进度条 -->
    <view class="progress-section">
      <view class="progress-header">
        <text>任务按时完成情况</text>
        <text>{{ onTimeCompleted }}/{{ completedTasks }} 任务</text>
      </view>
      <progress :percent="onTimeRate" activeColor="#6b9273" backgroundColor="#e9ecef" stroke-width="12" />
    </view>
    
    <!-- 最近一周完成情况 -->
    <view class="section">
      <view class="section-header">
        <text class="section-title">最近一周完成情况</text>
      </view>
      <view class="week-stats">
        <view v-for="(day, index) in lastWeekDays" :key="index" class="day-item">
          <text class="day-name">{{ day.name }}</text>
          <view class="day-bar-container">
            <view class="day-bar" :style="{ height: day.height + 'px' }"></view>
          </view>
          <text class="day-count">{{ day.count || 0 }}</text>
        </view>
      </view>
    </view>
    
    <!-- 任务优先级分布 -->
    <view class="section">
      <view class="section-header">
        <text class="section-title">任务优先级分布</text>
      </view>
      <view class="priority-distribution">
        <view v-for="(item, index) in priorityStats" :key="index" class="priority-item">
          <view class="priority-marker" :class="'priority-' + item.level"></view>
          <text class="priority-label">{{ item.label }}</text>
          <text class="priority-count">{{ item.count }} 任务</text>
          <text class="priority-percent">{{ item.percent }}%</text>
        </view>
      </view>
    </view>
    
    <!-- 最近完成的任务列表 -->
    <view class="section">
      <view class="section-header">
        <text class="section-title">最近完成的任务</text>
        <text class="view-all" @click="viewAllTasks">查看全部</text>
      </view>
      <view class="recent-tasks">
        <view v-for="(task, index) in recentCompletedTasks" :key="task.id" class="task-item">
          <view class="task-info">
            <text class="task-title">{{ task.title }}</text>
            <text class="task-time">{{ formatTime(task.completedAt) }}</text>
          </view>
          <view class="task-priority" :class="'priority-' + task.priority">
            {{ ['低', '中', '高'][task.priority-1] }}
          </view>
        </view>
      </view>
    </view>
    
    <!-- 数据更新时间 -->
    <view class="data-update">
      <text>数据更新于 {{ currentDate }} {{ currentTime }}</text>
      <view class="refresh-btn" @click="refreshData">
        <uni-icons type="refresh" size="16" color="#7a9bb5"></uni-icons>
        <text>刷新数据</text>
      </view>
    </view>
  </view>
</template>

<script>
export default {
  data() {
    return {
      memos: [],
      totalTasks: 0,
      completedTasks: 0,
      onTimeCompleted: 0,
      onTimeRate: 0,
      lastWeekDays: [],
      priorityStats: [
        { level: 1, label: '低优先级', count: 0, percent: 0 },
        { level: 2, label: '中优先级', count: 0, percent: 0 },
        { level: 3, label: '高优先级', count: 0, percent: 0 }
      ],
      recentCompletedTasks: [],
      currentDate: '',
      currentTime: ''
    };
  },
  onShow() {
    // 从本地存储加载数据
    this.loadMemos();
    // 更新当前时间
    this.updateCurrentDateTime();
  },
  methods: {
    // 从本地存储加载备忘录
    loadMemos() {
      const memos = uni.getStorageSync('memos') || [];
      this.memos = memos;
      this.calculateStats();
    },
    
    // 计算所有统计数据
    calculateStats() {
      this.totalTasks = this.memos.length;
      
      // 筛选已完成的任务
      const completedMemos = this.memos.filter(m => m.completed && m.completedAt);
      this.completedTasks = completedMemos.length;
      
      // 计算按时完成的任务数
      this.onTimeCompleted = completedMemos.filter(m => {
        // 没有截止日期或完成日期的任务不计入按时完成
        if (!m.dueDate || !m.completedAt) return false;
        
        const dueDate = new Date(m.dueDate);
        const completedDate = new Date(m.completedAt);
        return completedDate <= dueDate;
      }).length;
      
      // 计算按时完成率
      this.onTimeRate = this.completedTasks > 0 
        ? Math.round((this.onTimeCompleted / this.completedTasks) * 100) 
        : 0;
      
      // 计算最近一周完成情况
      this.calculateLastWeekStats(completedMemos);
      
      // 计算优先级分布
      this.calculatePriorityStats();
      
      // 获取最近完成的任务
      this.getRecentCompletedTasks(completedMemos);
    },
    
    // 计算最近一周完成情况
    calculateLastWeekStats(completedMemos) {
      const days = [];
      const today = new Date();
      const weekDays = ['日', '一', '二', '三', '四', '五', '六'];
       // 获取最近7天的日期（包括今天）
           for (let i = 0; i < 7; i++) {
              // 计算日期：从6天前（i=0）到当天（i=6）
              const date = new Date(today);
              date.setDate(date.getDate() - (6 - i)); // 注意：这样i=0时是6天前，i=6时是今天
              const dateStr = this.formatDate(date);
        
        // 统计当天完成的任务数
               const count = completedMemos.filter(m => {
                 if (!m.completedAt) return false;
                 const completedDate = new Date(m.completedAt);
                 return this.formatDate(completedDate) === dateStr;
               }).length;
        // 获取星期几
                const dayOfWeek = date.getDay();
                const dayName = weekDays[dayOfWeek];
                
                // 先放入数组，高度稍后计算（因为需要先知道最大值）
                days.push({ name: dayName, count, height: 0, date: dateStr });
             }
        // 计算最大任务数（用于归一化高度）
             const maxCount = Math.max(...days.map(d => d.count), 1); // 避免除以0
             
             // 计算每个柱子的高度（最大高度80px）
             days.forEach(day => {
                day.height = Math.round((day.count / maxCount) * 80);
             });
             
             this.lastWeekDays = days;
           },
    
    // 计算优先级分布
    calculatePriorityStats() {
      const stats = [...this.priorityStats];
      
      // 统计每个优先级的任务数
      stats.forEach(item => {
        item.count = this.memos.filter(m => m.priority === item.level).length;
      });
      
      // 计算每个优先级的百分比
      const total = this.totalTasks || 1;
      stats.forEach(item => {
        item.percent = Math.round((item.count / total) * 100);
      });
      
      this.priorityStats = stats;
    },
    
    // 获取最近完成的任务
    getRecentCompletedTasks(completedMemos) {
      // 按完成时间倒序排序
      const recentTasks = [...completedMemos]
        .filter(m => m.completedAt)
        .sort((a, b) => new Date(b.completedAt) - new Date(a.completedAt))
        .slice(0, 5);
      
      this.recentCompletedTasks = recentTasks;
    },
    
    // 格式化时间显示
    formatTime(dateString) {
      if (!dateString) return '';
      const date = new Date(dateString);
      return `${date.getFullYear()}-${(date.getMonth()+1).toString().padStart(2, '0')}-${date.getDate().toString().padStart(2, '0')}`;
    },
    
    // 格式化日期
    formatDate(date) {
      return `${date.getFullYear()}-${(date.getMonth()+1).toString().padStart(2, '0')}-${date.getDate().toString().padStart(2, '0')}`;
    },
    
    // 更新当前日期时间
    updateCurrentDateTime() {
      const now = new Date();
      this.currentDate = this.formatDate(now);
      this.currentTime = `${now.getHours().toString().padStart(2, '0')}:${now.getMinutes().toString().padStart(2, '0')}`;
    },
    
    // 查看所有任务
    viewAllTasks() {
      uni.switchTab({
        url: '/pages/note/index'
      });
    },
    
    // 刷新数据
    refreshData() {
      uni.showLoading({
        title: '刷新中...',
        mask: true
      });
      
      setTimeout(() => {
        this.loadMemos();
        this.updateCurrentDateTime();
        uni.hideLoading();
        uni.showToast({
          title: '数据已刷新',
          icon: 'success'
        });
      }, 800);
    }
  }
};
</script>

<style lang="scss" scoped>
/* 使用全局颜色变量 */
$primary-morandi: #7a9bb5;
$primary-morandi-active: #5a7c95;
$secondary-blue: #8ea4b6;
$secondary-green: #97a79c;
$secondary-purple: #a08eb5;
$neutral-white: #f9fafb;
$neutral-light: #e9ecef;
$neutral-medium: #ced4da;
$neutral-dark: #495057;
$neutral-black: #212529;
$status-success: #6b9273;
$status-warning: #d4b876;
$status-error: #c47a7a;

/* 字体大小 */
$font-size-xs: 24upx;
$font-size-sm: 28upx;
$font-size-base: 32upx;
$font-size-lg: 36upx;
$font-size-xl: 40upx;

/* 字体粗细 */
$font-weight-light: 300;
$font-weight-normal: 400;
$font-weight-bold: 600;
$font-weight-bolder: 700;

/* 圆角 */
$border-radius-sm: 8upx;
$border-radius-md: 16upx;
$border-radius-lg: 24upx;

/* 阴影 */
$box-shadow: 0 4upx 20upx rgba(0, 0, 0, 0.05);

.stats-container {
  padding: 30upx;
  background-color: $neutral-white;
  min-height: 100vh;
}

.stats-header {
  text-align: center;
  margin-bottom: 40upx;
  .stats-title {
    font-size: $font-size-xl;
    font-weight: $font-weight-bold;
    color: $neutral-black;
    display: block;
    margin-bottom: 16upx;
  }
  .stats-subtitle {
    font-size: $font-size-sm;
    color: $neutral-dark;
  }
}

.overview-cards {
  display: flex;
  justify-content: space-between;
  margin-bottom: 40upx;
  .stat-card {
    flex: 1;
    background-color: $neutral-white;
    border-radius: $border-radius-md;
    padding: 30upx;
    margin: 0 10upx;
    display: flex;
    flex-direction: column;
    align-items: center;
    box-shadow: $box-shadow;
    border: 1px solid $neutral-light;
    
    .card-icon {
      width: 80upx;
      height: 80upx;
      border-radius: 50%;
      display: flex;
      align-items: center;
      justify-content: center;
      margin-bottom: 20upx;
      background-color: rgba($primary-morandi, 0.1);
    }
    
    .card-value {
      font-size: $font-size-xl;
      font-weight: $font-weight-bold;
      color: $neutral-black;
      margin-bottom: 10upx;
    }
    
    .card-label {
      font-size: $font-size-sm;
      color: $neutral-dark;
    }
  }
}

.progress-section {
  background-color: $neutral-white;
  border-radius: $border-radius-md;
  padding: 30upx;
  margin-bottom: 30upx;
  box-shadow: $box-shadow;
  border: 1px solid $neutral-light;
  
  .progress-header {
    display: flex;
    justify-content: space-between;
    margin-bottom: 30upx;
    font-size: $font-size-base;
    color: $neutral-dark;
  }
}

.section {
  background-color: $neutral-white;
  border-radius: $border-radius-md;
  padding: 30upx;
  margin-bottom: 30upx;
  box-shadow: $box-shadow;
  border: 1px solid $neutral-light;
  
  .section-header {
    display: flex;
    justify-content: space-between;
    align-items: center;
    margin-bottom: 30upx;
    
    .section-title {
      font-size: $font-size-lg;
      font-weight: $font-weight-bold;
      color: $neutral-black;
      position: relative;
      padding-left: 20upx;
      
      &::before {
        content: '';
        position: absolute;
        left: 0;
        top: 50%;
        transform: translateY(-50%);
        width: 8upx;
        height: 32upx;
        background: $primary-morandi;
        border-radius: 4upx;
      }
    }
    
    .view-all {
      font-size: $font-size-sm;
      color: $primary-morandi;
    }
  }
}

.week-stats {
  display: flex;
  justify-content: space-between;
  
  .day-item {
    display: flex;
    flex-direction: column;
    align-items: center;
    flex: 1;
    
    .day-name {
      font-size: $font-size-sm;
      color: $neutral-dark;
      margin-bottom: 16upx;
    }
    
    .day-bar-container {
      height: 160upx;
      display: flex;
      align-items: flex-end;
      margin-bottom: 16upx;
    }
    
    .day-bar {
      width: 40upx;
      background-color: $secondary-blue;
      border-radius: 8upx 8upx 0 0;
      transition: height 0.5s ease;
    }
    
    .day-count {
      font-size: $font-size-sm;
      font-weight: $font-weight-bold;
      color: $neutral-black;
    }
  }
}

.priority-distribution {
  .priority-item {
    display: flex;
    align-items: center;
    padding: 24upx 0;
    border-bottom: 1px solid $neutral-light;
    
    &:last-child {
      border-bottom: none;
    }
    
    .priority-marker {
      width: 24upx;
      height: 24upx;
      border-radius: 50%;
      margin-right: 20upx;
      
      &.priority-1 {
        background-color: $secondary-blue;
      }
      
      &.priority-2 {
        background-color: $primary-morandi;
      }
      
      &.priority-3 {
        background-color: $secondary-purple;
      }
    }
    
    .priority-label {
      flex: 1;
      font-size: $font-size-base;
      color: $neutral-black;
    }
    
    .priority-count {
      font-size: $font-size-base;
      color: $neutral-dark;
      margin-right: 20upx;
    }
    
    .priority-percent {
      font-size: $font-size-base;
      font-weight: $font-weight-bold;
      color: $primary-morandi;
      width: 80upx;
      text-align: right;
    }
  }
}

.recent-tasks {
  .task-item {
    display: flex;
    justify-content: space-between;
    align-items: center;
    padding: 24upx 0;
    border-bottom: 1px solid $neutral-light;
    
    &:last-child {
      border-bottom: none;
    }
    
    .task-info {
      flex: 1;
    }
    
    .task-title {
      font-size: $font-size-base;
      color: $neutral-black;
      display: block;
      margin-bottom: 8upx;
      font-weight: $font-weight-bold;
    }
    
    .task-time {
      font-size: $font-size-sm;
      color: $neutral-dark;
    }
    
    .task-priority {
      padding: 8upx 20upx;
      border-radius: 24upx;
      font-size: $font-size-sm;
      font-weight: $font-weight-bold;
      
      &.priority-1 {
        background-color: rgba($secondary-blue, 0.15);
        color: $secondary-blue;
      }
      
      &.priority-2 {
        background-color: rgba($primary-morandi, 0.15);
        color: $primary-morandi;
      }
      
      &.priority-3 {
        background-color: rgba($secondary-purple, 0.15);
        color: $secondary-purple;
      }
    }
  }
}

.data-update {
  display: flex;
  justify-content: space-between;
  align-items: center;
  font-size: $font-size-sm;
  color: $neutral-dark;
  padding: 20upx 0;
  
  .refresh-btn {
    display: flex;
    align-items: center;
    color: $primary-morandi;
    
    text {
      margin-left: 10upx;
    }
  }
}
</style>